#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

int main(){
    key_t key = ftok(".", 'A');
    if(key == -1){
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    int semid = semget(key, 2, IPC_CREAT | 0666 | IPC_EXCL);
    if (semid == -1) {
        if (errno == EEXIST) {
            // 如果信号量集合已经存在，则打开它
            semid = semget(key, 2, 0666);
            if (semid == -1) {
                perror("semget");
                exit(EXIT_FAILURE);
            }
        } else {
            perror("semget");
            exit(EXIT_FAILURE);
        }
    } else {
        unsigned short num[2] ={2, 0};
        //初始化信号量集合
        if (semctl(semid, 0, SETALL, num) == -1) {
            perror("semctl");
            exit(EXIT_FAILURE);
        }
    }
    printf("create or open semaphore success!\n");
    //删除信号量集合
    semctl(semid, 0, IPC_RMID);

    return 0;
}